package com.cjl.multi_thread.share_cooperate.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class UseLock implements GoodsService{
    private GoodsInfo goodsInfo;

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.WriteLock  writeLock = lock.writeLock();
    private final ReentrantReadWriteLock.ReadLock  readLock = lock.readLock();

    public UseLock(GoodsInfo goodsInfo) {
        this.goodsInfo = goodsInfo;
    }

    @Override
    public GoodsInfo getInfo() {
        readLock.lock();
        try {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return goodsInfo;
        }finally {
            readLock.unlock();
        }
  }

    @Override
    public void setNum(int num) {
        writeLock.lock();
        try {
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            goodsInfo.changeNumber(num);
        }finally {
            writeLock.unlock();
        }
    }
}
